﻿using FeedingReport.Commands;
using FeedingReport.Configs;
using hyjx.bind;
using Hyjx.GF.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace FeedingReport.ViewModels
{
    public class InitializePageViewModel : BindableBase
    {
        string _tips = string.Empty;
        public string Tips { get => _tips; set => SetProperty(ref _tips, value); }

        Visibility _exitButtonVisibility = Visibility.Collapsed;

        public Visibility ExitButtonVisibility { get => _exitButtonVisibility; set => SetProperty(ref _exitButtonVisibility, value); }


        public ExitCommand ExitCommand { get; } = new();

        public async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Tips = "读取配置……";
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json").Build();

                App.Materials = configuration.GetSection("MaterialCodes").Get<MaterialCodeConfig[]>();
                App.Mixers = configuration.GetSection("RelatedMixers").Get<string[]>();

                IConfigurationRoot con = new ConfigurationBuilder()
                            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                            .AddJsonFile("DBsettings.json").Build();

                string? dbPath = con["GFDB:Path"];
                if (string.IsNullOrEmpty(dbPath))
                    return;

                App.DbConnectionString = $"Filename={dbPath};Password={con["GFDB:Password"]}";

                Tips += "完成。";

                Tips = "初始化数据库……";
                using GFDbContext db = new(App.DbConnectionString);
                await db.Database.MigrateAsync();
                Tips += "完成。";

                App.Navigate("ReportPage.xaml"); // 跳转到报表页面
            }
            catch(Exception ex)
            {
                Tips = ex.Message;
                ExitButtonVisibility = Visibility.Visible;
            }
        }
    }
}
